import { useBoolean } from '@gnlab/utils/env-react'
import { Button, Checkbox, Tooltip } from 'antd'
import type { CheckboxChangeEvent } from 'antd/lib/checkbox'
import config from '@/config'
import { Modal, Link } from '@/desktop/components'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { AuthMethod } from '@/services/auth'

export function Account() {
  const [account] = useStreams(services.auth.account$)

  const logout = useCallback(() => {
    if (!account) return
    if (account.method === AuthMethod.apps) void services.auth.apps.logout()
    else services.auth.internal.logout()
  }, [account])

  const [confirming, startConfirming, finishConfirming] = useBoolean(false)
  const confirmed = useCallback(
    (shouldLogout: boolean, shouldDestroy: boolean) => {
      finishConfirming()
      if (!shouldLogout) return
      if (shouldDestroy) services.qywxs.logoutAll()
      setTimeout(() => logout(), 100) // 涉及页面跳转，为保证前面操作有效，设个 timeout
    },
    [finishConfirming, logout],
  )

  if (!account) return null

  const infoUrl = encodeURIComponent(`${config.ACCOUNT_BASE_URL}/info`)
  const url = `${config.ACCOUNT_BASE_URL}/login?token=${account.token}&redirect_uri=${infoUrl}`
  const tooltip = <div css={styles.tooltip}>
    {account.method === AuthMethod.apps ? (
      <Link className="name" href={url}>
        <Button type="primary">查看账号信息</Button>
      </Link>
    ) : null}

    <Button danger onClick={startConfirming}>
      退出
    </Button>
  </div>

  return <Tooltip title={tooltip} color="#fff">
    <div css={styles.account}>
      <img src={account.avatar || defaultAvatar} />
      <span className="nickname">{account.name || account.id}</span>
    </div>
    <ConfirmModal open={confirming} confirmed={confirmed} />
  </Tooltip>
}

function ConfirmModal(props: {
  open: boolean
  confirmed: (logout: boolean, destroy: boolean) => void
}) {
  const { confirmed, open } = props
  const [destroy, setDestroy] = useState(false)
  const onChange = useCallback((e: CheckboxChangeEvent) => setDestroy(e.target.checked), [])
  const onCancel = useCallback(() => confirmed(false, false), [confirmed])
  const onOk = useCallback(() => confirmed(true, destroy), [confirmed, destroy])

  return <Modal open={open} title="确定要退出吗？" onCancel={onCancel} onOk={onOk}>
    <Checkbox checked={destroy} onChange={onChange}>
      同时退出已登录的企业微信
    </Checkbox>
  </Modal>
}

const styles = {
  account: css`
    align-items: center;
    cursor: default;
    display: flex;
    margin-left: 10px;
    padding-left: 10px;
    img {
      border-radius: 24px;
      height: 24px;
      margin-right: 8px;
      width: 24px;
    }
    .nickname {
      color: rgba(0, 0, 0, 0.65);
    }
  `,
  tooltip: css`
    display: flex;
    flex-direction: column;
    padding: 6px;
    row-gap: 10px;
    width: 140px;
    button {
      width: 100%;
    }
  `,
}
